package com.yoda.mall.mysql.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.mall.api.RoleApi;
import com.yoda.mall.api.RoleMenuRelationApi;
import com.yoda.mall.api.RolePermissionRelationApi;
import com.yoda.mall.api.RoleResourceRelationApi;
import com.yoda.mall.model.entity.ums.Role;
import com.yoda.mall.model.vo.PageResult;
import com.yoda.mall.mysql.mapper.RoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;

@DubboService
public class RoleApiImpl implements RoleApi {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuRelationApi roleMenuRelationApi;
    @Resource
    private RoleResourceRelationApi roleResourceRelationApi;
    @Resource
    private RolePermissionRelationApi rolePermissionRelationApi;

    @Override
    public PageResult<Role> pageList(String keyword, Integer pageNum, Integer pageSize) {
        Page<Role> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(keyword),Role::getName,keyword).orderByAsc(Role::getId);
        roleMapper.selectPage(page, wrapper);
        return new  PageResult<Role>(pageNum,pageSize,Convert.toInt(page.getTotal()),page.getRecords());
    }

    @Override
    public List<Role> listAll() {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Role::getId);
        return roleMapper.selectList(wrapper);
    }

    @Override
    public void updateById(Integer id, Role role) {
        role.setId(Convert.toLong(id));
        roleMapper.updateById(role);
    }

    @Override
    public void create(Role role) {
        roleMapper.insert(role);
    }

    /**
     * 删除角色，删除角色对应的菜单，资源
     * @param ids
     */
    @Override
    public void deleteByIds(int[] ids) {
        for (int id : ids) {
            roleMapper.deleteById(id);
            roleMenuRelationApi.deleteByRoleId(id);
            rolePermissionRelationApi.deleteByRoleId(id);
            roleResourceRelationApi.deleteByRoleId(id);
        }
    }
}
